`
https://leetcode.cn/problems/maximum-points-you-can-obtain-from-cards/
`

/**
 * @param {number[]} cardPoints
 * @param {number} k
 * @return {number}
 */
var maxScore = function (cardPoints, k) {
  const n = cardPoints.length
  const sum = cardPoints.reduce((acc, cur) => acc + cur)
  // 题目等价为：计算长为 n - k 的子数组和的最小值
  k = n - k
  // 如果需要维护的滑动窗口长度为 0，那么直接返回数组和即可
  // 否则会导致下面滑动窗口实际上维护的是长度为 1 的窗口
  if (k === 0) return sum
  let windowSum = 0
  let minSum = Infinity
  let left = 0, right = 0

  // 维护一个长度为 n - k 的滑动窗口
  while (right < n) {
    const n1 = cardPoints[right++]
    windowSum += n1

    if (right - left >= k) {
      minSum = Math.min(minSum, windowSum)
      const n2 = cardPoints[left++]
      windowSum -= n2
    }
  }

  return sum - minSum
};